package com.feature.learn.concurrent.Semaphore.sampe1;

import cn.hutool.core.date.DateUtil;

import java.text.SimpleDateFormat;
import java.util.concurrent.Semaphore;

/**
 * @author 01390942
 * @Description
 * @create 2021/7/2
 * @since 1.0.0
 */
public class SemaphoreService {
    private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private Semaphore semaphore = null;// 同步关键类，构造方法传入的数字是多少，则同一个时刻，只运行多少个进程同时运行制定代码

    public SemaphoreService(int count) {
        this.semaphore = new Semaphore(count);
    }

    public void doSomething() {
        try {
            // 获得信号，同一时刻只允许指定个数（new Semaphore(1)）的线程同时执行后续代码
            semaphore.acquire();

            System.out.println(Thread.currentThread().getName() + ": doSomething start - " + DateUtil.now());
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + ": doSomething end - " + DateUtil.now());

            // 取消信号
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}